package com.bird.common.utils.covert;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.databind.util.StdConverter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 系统用户转换
 *
 * @author: 李涛
 * @version: 2020年02月14日 17:46
 */
@Slf4j
public class SystemUserCovert extends StdConverter<Long, SystemUserCovert.SystemUserSimple> {

	/**
	 * 字典翻译的bean引用
	 */
	public static final Object SYS_USER_SPRINGBEAN = SpringUtil.getBean("sysUserServiceImpl");

	/**
	 * 已存在的用户
	 */
	private static Map<Long, SystemUserSimple> existUser = new ConcurrentHashMap();

	/**
	 * 错误查找的用户，30分钟失效
	 */
	private static TimedCache<Long, String> errorUser = CacheUtil.newTimedCache(TimeUnit.MINUTES.toMillis(30));

	@Override
	public SystemUserSimple convert(Long id) {
		if (id == null || id < 0) {
			return null;
		}
		if (errorUser.containsKey(id)) {
			log.error("Cache-用户{}-姓名查找失败!", id);
			return null;
		}
		SystemUserSimple systemUserSimple = existUser.get(id);
		if (systemUserSimple == null) {
			systemUserSimple = new SystemUserSimple();
			systemUserSimple.setId(id);
			String userName = ReflectUtil.invoke(SYS_USER_SPRINGBEAN, "selectUserNameById", id);
			if (userName != null && userName.length() < 20) {
				// 名字规范才设置
				systemUserSimple.setName(userName);
				existUser.put(id, systemUserSimple);
			} else {
				errorUser.put(id, id.toString());
				log.error("http-用户{}-姓名查找失败!", id);
			}

		}
		return systemUserSimple;
	}

	/**
	 * 系统用户
	 */
	@Data
	public static class SystemUserSimple {

		private Long id;

		private String name;

	}
}
